//
//  Fence.swift
//  ShareCar
//
//  Created by lishuai on 2018/8/24.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation

struct Geo: Codable {
    
    struct Item: Codable {
        let type: String
        let districtCode: String
        let radiusNum: Double
        let coordinates: [[String]]
        
        enum CodingKeys : String, CodingKey {
            case type = "type"
            case districtCode = "district_code"
            case radiusNum = "radius_num"
            case coordinates = "coordinates"
        }
    }
    
    let time: Int
    let list: [Item]
}

struct Fence: Codable {
    let configValue: String
    let updatedAt: Int
    
    enum CodingKeys : String, CodingKey {
        case configValue = "config_value"
        case updatedAt = "updated_at"
    }
}

extension Fence {
    static func fence() {
        Base<Fence>.request(URIString: "detection_fence", success: { data in
            if let data = data {
                DispatchQueue.global().async {
                    update(data)
                }
            }
        }) { error, data in
            p(error)
        }
    }
    
    static func update(_ fence: Fence) {
        let updatedAt = UserDefaults.standard.integer(forKey: "fence.update_at")
        if fence.updatedAt != updatedAt {
            if let url = URL(string: kImageServerName + fence.configValue) {
                do {
                    let json = try String(contentsOf: url)
                    let filePath = NSHomeDirectory() + "/Documents/fence.json"
                    try json.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
                    UserDefaults.standard.set(fence.updatedAt, forKey: "fence.update_at")
                } catch {
                    p(error)
                }
            }
        }
    }
    
    static func readGeoJson() -> Geo? {
        if let url = URL(string: "file://" + NSHomeDirectory() + "/Documents/fence.json") {
            do {
                let data = try Data(contentsOf: url)
                let geo = try JSONDecoder().decode(Geo.self, from: data)
                return geo
            } catch {
                p(error)
            }
        }
        return nil
    }
}
